解答1[Java]:

class Solution {
    public int majorityElement(int[] nums) {
        int count = 0;
        Integer candidate = null;

        for (int num : nums) {
            if (count == 0) {
                candidate = num;
            }
            count += (num == candidate) ? 1 : -1;
        }

        return candidate;
    }
}

思路

这个算法叫做摩尔计数法(Boyer-Moore Voting Algorithm)。

选定一个数,遇到相同的就加1,不同就减1,count 变成 0 就换下一个数,因为众数占总体的一半以上,所以众数总能脱颖而出。

解答2[Java]:

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length / 2];
    }
}

思路

这个算法的原理是,数组排序之后,众数一定位于 n/2 左右。

results matching ""

    No results matching ""